#delimit cr
clear
clear mata
clear matrix
set maxvar 15000
set more off
pause on
local tempdir "$temp"

global singleRun = 0
global runs = 411
global numParams = 8
global variables cons assEnd Y annProp
global numsims 2848

if $singleRun == 0 {
		infile param using "$fortranInputs\inputParamsMain.txt", clear
		gen runningCount = _n
		gen run =floor((runningCount - 1)/$numParams)  + 1
		bys run: gen id = _n
		drop runningCount
		reshape wide param, i(run) j(id)
		
		rename param1 beta
		rename param2 gamma
		rename param3 objective
		rename param4 addMinLoad
		rename param5 housing		
		rename param6 annOn		
		rename param7 unscaled		
		rename param8 annuityDiscreteChoice

		/* Generate indexes */
		foreach param of varlist beta gamma objective addMinLoad housing annOn unscaled annuityDiscreteChoice {
				egen ix`param' = group(`param')
			}
		
		save "`tempdir'\paramDets", replace

		global howManyRuns = $runs
		}
		else {
		global howManyRuns = 1		
		}
		

forvalues ixR = 1/$howManyRuns {

	/* Read each output in and save as a temp file*/
		
		if $singleRun == 1 {
			global simpath "$simMasterPath"
			}
		else {
			global simpath "$simMasterPath\\`ixR'\"
		}
			
		
		local index = 1
	quietly {
			foreach output in  $variables  {
								infile `output' using "$simpath\\`output'.out", clear
								gen runningCount = _n
								gen time = floor((runningCount - 1)/$numsims)  + 1
								bys time: gen id = _n
								drop runningCount
								
								save "`tempdir'\\`output'", replace

								if `index' == 1 { /*Get a file with just the ids and time*/
									keep id time 
									save "`tempdir'\id", replace
									local index = 0
								}
							
							}

	use "`tempdir'\id", replace

			foreach output in   $variables  {
								di "`output'"
								merge 1:1 id time using "`tempdir'\\`output'", assert(3)
								drop _m
								}

								
	/* Merge in parameter details*/
	if $singleRun== 0 {
		gen run = `ixR'
		merge m:1 run using "`tempdir'\paramDets", assert(2 3) keep(3)
		drop _m
		}
	save "$simpath\runMicroData`ixR'", replace
	}
	di `ixR'
}
if $singleRun== 0 {
	clear
	/*Merge all the runs together */
	forvalues ixR = 1/$howManyRuns {		
		global simpath "$simMasterPath\\`ixR'\"
		append using "$simpath\runMicroData`ixR'"
	}
	save "$simMasterPath\allRunsMicroData", replace
}

exit
	